/* Copyright 2010 Hugh Greenberg */   

package com.hugegreenbug.msoss;

import com.hugegreenbug.msoss.R;

import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.provider.MediaStore;

public class MsSettings extends PreferenceActivity 
	implements SharedPreferences.OnSharedPreferenceChangeListener{ 
	private String mCubeBg;
	
    @Override
    protected void onCreate(Bundle bund) {
    	super.onCreate(bund);
    	getPreferenceManager().setSharedPreferencesName(
    			Ms.msEngine.SHARED_PREFS_NAME);
    	addPreferencesFromResource(R.xml.ms_settings);
    	getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
    	mCubeBg = getPreferenceManager().getSharedPreferences().getString("ms_cube_bg", "heic0719a");
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
    	 getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(
                 this);
        super.onDestroy();
    }
    
    public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
    	if (key.equals("ms_cube_bg")) {

			String newS = prefs.getString("ms_cube_bg", "heic0719a");
			if (!newS.equals(mCubeBg) && newS.equals("custom_background")) {
				Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
				intent.setType("image/*");
				startActivityForResult(intent, 0);
			}	
			
			mCubeBg = newS;
    	}
    }
    
    protected void onActivityResult(int requestCode, int resultCode, 
    		Intent imageReturnedIntent) {
        super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
        SharedPreferences settings = getSharedPreferences(Ms.msEngine.SHARED_PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        
        switch(requestCode) {
        case 0:
            if(resultCode == RESULT_OK) {             	
    			mCubeBg = "custom_background";
                Uri selectedImage = imageReturnedIntent.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                Cursor cursor = getContentResolver().query(selectedImage, 
                		filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String filePath = cursor.getString(columnIndex);
                
                cursor.close();
              
                editor.putString("ms_custom_background_uri", filePath);
                editor.commit();
            } 
        }
    }
}
